import { app, createHttpsServer } from './httpServer/httpServer';
import './httpServer/controllers/user';
import './webSocketServer/server';
import { globalConfig } from './config';
import { readFileSync } from 'node:fs';
import { Server } from 'socket.io';
import { WSSServer } from './webSocketServer/server';

//从全局配置中获取SSL证书和私钥文件
const privateKey = readFileSync(globalConfig.sslPrivateKey, 'utf8');
const certificate = readFileSync(globalConfig.sslCertificate, 'utf8');

//配置自签名证书
const credentials = { key: privateKey, cert: certificate };

const httpsServer = createHttpsServer(credentials, app);

const io = new Server(httpsServer, {
  cors: {
    origin: [
      'https://localhost:443',
      'wss://localhost:443',
      'http://localhost:5173'
    ],
    methods: ['GET', 'POST']
  }
});

/**
 * 初始化WebSocket消息分发模块
 */
const wssServer = new WSSServer(io);
wssServer.init();

//启动服务器并监听443端口
httpsServer.listen(globalConfig.port, () => {
  console.log(`https://localhost:${globalConfig.port}`);
});
